<template>
	<view class="login-box">
		<view class="logo">
			<image src="@/static/logo.png" mode="aspectFit"></image>
		</view>
		<view class="desc">
		</view>
		<view class="form">
			<view class="form_item">
				<view class="label">手机号</view>
				<input class="inp1" type="number" v-model="phone" placeholder="请输入手机号码" />
			</view>
			<view class="form_item">
				<view class="label">密码</view>
				<input class="inp1" password="true" v-model="password" placeholder="请输入密码" />
			</view>
		</view>
		<view style="padding-top: 76rpx;">
			<button class="btn" @click="userLogin()">登录</button>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="other-login">
			<view class="ol-tilte">
				<text>快捷登录</text>
			</view>


			<button class="phonelogin" v-if="!puserInfo.phone" open-type="getPhoneNumber"
				@getphonenumber="miniWechatLoginb">手机号快捷登陆</button>

		</view>


		<!-- #endif -->

		<view class="popup-box" v-show="showPopup">
			<view class="login-popup">
				<view class="lp-top">
					<view class="lpt-left">
						<view class="title"> <text>登录</text> </view>
						<view class="tips"> <text>登录即可解锁更多权益</text> </view>
					</view>
					<view class="lpt-right" @click="showPopup=false">
						<u-icon name="close"></u-icon>
					</view>
				</view>

				<view class="lp-center">
					<view class="title">申请获取以下权限</view>
					<view class="tips">获得你的公开信息（昵称、头像等）</view>
					<view class="tips">获得你的手机号码</view>
				</view>

				<view class="lp-bottom">
					<!-- getUserInfo -->
					<button class="option-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
						获取手机号
					</button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import appConfig from "@/config/appConfig.js";
	export default {
		data() {
			return {
				phone: '',
				password: '',
				appConfig,
				showLoding: true, // 初始化加载时显示遮挡页
				wxUserInfo: null, // 保存微信用户数据(临时)
				wxLoginInfo: {
					code: null,
					openid: null,
					session_key: null
				}, // 微信登录返回信息（临时）
				showPopup: false, // 获取电话弹窗
			}
		},
		onShareAppMessage() {
			return {
				title: '清能回收员',
				path: '/pages/home/home',
				imageUrl: '/static/logo.png'
			}
		},
		onShareTimeline: function() {
			return {
				title: "清能回收员",
				imageUrl: '/static/logo.png',
				path: `/pages/home/home`
			}
		},

		onLoad() {
			this.initLogin();
		},
		computed: {
			...mapState(['token'])
		},
		methods: {
			...mapMutations(['saveUserInfo', 'sessionToken']),
			//授权手机号登录
			miniWechatLoginb(e) {
				const that = this
				// if (that.checkType === 0) {
				//     that.$api.msg('请勾选注册协议与隐私协议')
				//     return
				// }
				console.log(e, '2222222222222222')
				uni.showLoading({})
				if (e.detail.errMsg != "getPhoneNumber:ok") {
					uni.hideLoading()
					return
				}
				uni.login({
					provider: 'weixin',
					success: (wxres => {
						console.log(wxres, 'wxres111111111111')
						this.logining = false
						var param = {
							encryptedData: e.detail.encryptedData,
							iv: e.detail.iv,
							code: wxres.code
						}
						console.log(param, 'param')
						that.request("get", "rider/wxLogin/miniPhoneLogin", null, param).then(res => {
							if (res.code === 200) {
								// 至此实际已登录
								that.wxLoginInfo.openid = res.data.openId;
								that.wxLoginInfo.session_key = res.data.sessionKey;
								// 保存数据库返回的用户信息

								// if (type === 1) {
								// 	// 返回无token, 另需获取手机号绑定对应的openid
								// 	that.showPopup = true; // 显示获取手机号按钮
								// } else {
									// 返回带token, 进入订单页
									let duration = 1500; // 延迟跳转页面
									uni.setStorageSync("token", res.data.accessToken)
									that.saveUserInfo(res.data); // 缓存用户基础数据
									that.sessionToken(res.data.accessToken); // 缓存token
									uni.showToast({
										title: '登录成功',
										duration
									})
									that.toTaskPage(duration);
								// }
							} else {
								uni.showToast({
									title: res.msg
								})
							}
						})

						// that.$api.request('get', 'miniPhoneLogin', param, failres => {
						// 	that.$api.msg(failres.msg)
						// 	uni.hideLoading()
						// }).then(res => {
						// 	if(res.code === 200){
						// 		uni.setStorageSync('userInfo', res.data)
						// 		that.$store.commit('login', res.data)
						// 		uni.hideLoading()
						// 		uni.navigateBack({
						// 			delta:1
						// 		})
						// 	}
						// })
					})
				})

			},
			userLogin() {
				if (!(/^1[3456789]\d{9}$/.test(this.phone))) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					})
					return false;
				}
				if (this.password == '') {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					})
					return false;
				}

				let params = {
					phone: this.phone,
					password: this.password,
					ip: ''
				}
				let that = this
				that.request("get", "rider/app/loginRider", null, params).then(res => {
					if (res.code === 200) {
						// 返回带token, 进入订单页
						let duration = 1500; // 延迟跳转页面
						that.saveUserInfo(res.data); // 缓存用户基础数据
						let token = res.data.accessToken;
						uni.setStorageSync("token", token)
						that.sessionToken(res.data.accessToken); // 缓存token
						uni.showToast({
							title: '登录成功',
							duration
						})
						that.toTaskPage(duration);
					}
				})
			},

			/* 判断是否已登录 */
			async initLogin() {
				let that = this
				console.log('token', that.token)
				if (that.token) {
					let newUserData = await that.getUserInfo();
					if (newUserData) {
						that.saveUserInfo(newUserData); // 缓存用户基础数据
						that.toTaskPage();
					} else {
						that.showLoding = false;
					}
				} else {
					that.showLoding = false;
				}
			},
			onInput(e) {
				this.phone = e.target.value;
			},
			/* 前往任务列表页 */
			toTaskPage(duration = 100) {
				// debugger
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/home/home'
					})
				}, duration)
			},

			/* 获取后台用户信息（进入即判断是否过期） */
			getUserInfo() {
				let that = this;
				return new Promise((resolve, reject) => {
					that.request("get", "rider/wxLogin/getRiderInfo", that.token, null).then(res => {
						console.log('getUserInfo', res)
						if (res.code === 200) {
							resolve(res.data)
						} else {
							resolve(false)
						}
					})
				})
			},

			/* 获取微信用户信息（登录使用） */
			getUserProfile() {
				// #ifdef MP-WEIXIN
				let that = this;
				if (that.wxLoginInfo.openid) {
					// 已登录，但未获取手机号
					that.showPopup = true;
				} else if (uni.getUserProfile) {
					// 未登录，且版本支持 uni.getUserProfile
					uni.getUserProfile({
						lang: 'zh_CN',
						desc: "获取您的昵称、头像、手机号",
						success: async (res) => {
							console.log('用户同意了授权', res)
							that.wxUserInfo = res.userInfo; // 临时保存微信用户基础数据
							that.wxUserInfo['phone'] = '';
							that.mpWeixinTologin(); // 微信一键登录
						},
						fail: (err) => {
							console.log('授权失败:', err)
							uni.showToast({
								title: err
							})
						}
					})
				} else {
					uni.showToast({
						title: '当前版本过低'
					})
				}
				// #endif
				// #ifdef H5
				this.tempH5Login()
				// #endif
			},

			tempH5Login() {
				let data = {
					"accessToken": "29478626990E478DA9539866489DD87D",
					"avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epib9DbQJ7VsbLFhWMgiarZSibmRPXWb2tHOtzicnbzpj7Z8lIoBy6icUn0vESMicnMnv8lbGjxYKwSnspw/132",
					"deliveryEnd": "23:00",
					"deliveryStart": "8:30",
					"gmtCreate": 1666885726000,
					"gmtLastLogin": 1667054521000,
					"gmtUpdate": 1666885726000,
					"id": 151,
					"lastLoginIp": "27.10.60.71",
					"loginType": 1,
					"name": "L",
					"openId": "o7LCC5YUDftbpo907smJhvgsMnBs",
					"phone": "18522563339",
					"sessionKey": "yjKdFE0CMSLBKNmrXmFyyQ==",
					"state": 1,
					"storageId": 11,
					"workState": 1
				}
				let token = '29478626990E478DA9539866489DD87D';
				this.saveUserInfo(data); // 缓存用户基础数据
				this.sessionToken(token); // 缓存token
				this.toTaskPage(100);
			},

			/* 微信登录 */
			mpWeixinTologin() {
				let that = this;
				uni.login({
					provider: 'weixin',
					async success(res) {
						console.log('微信一键登录', res);
						if (res.errMsg == 'login:ok') {
							that.wxLoginInfo.code = res.code;
							that.serverLogin(1);
						}
					},
					fail(err) {
						console.log('uni.login', err);
					}
				});
			},

			/* 获取手机号 */
			getPhoneNumber(e) {
				console.log('获取手机号', e);
				let that = this;
				if (!that.wxLoginInfo.openid || !e.detail.encryptedData) {
					return false; // 未登录
				}
				that.showPopup = false; // 显示获取手机号按钮
				let content = {
					openid: that.wxLoginInfo.openid,
					sessionkey: that.wxLoginInfo.session_key,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
				}
				let params = {
					raw: JSON.stringify(content)
				};
				that.request("get", "rider/wxLogin/decryptS5", null, params).then(resolve => {
					console.log('获取解密手机号', resolve)
					if (resolve.code === 200) {
						// debugger
						let data = JSON.parse(resolve.data);
						that.wxUserInfo.phone = data.phoneNumber;
						that.serverLogin(2);
					} else {
						uni.showToast({
							title: resolve.msg
						})
					}
				})
			},

			/* 后台登录 */
			serverLogin(type) {
				// type: 1-第一次后台登录(返回无token) 2-第一次后台登录(返回带token)
				let that = this;
				let content = {
					code: that.wxLoginInfo.code,
					phone: that.wxUserInfo.phone,
					nickName: that.wxUserInfo.nickName,
					avatarUrl: that.wxUserInfo.avatarUrl,
					openid: that.wxLoginInfo.openid,
					session_key: that.wxLoginInfo.session_key,
				};
				that.request("post", "rider/wxLogin/wechatLogin", null, content).then(res => {
					console.log('获取数据库返回的用户信息', res);
					if (res.code === 200) {
						// 至此实际已登录
						that.wxLoginInfo.openid = res.data.openId;
						that.wxLoginInfo.session_key = res.data.sessionKey;
						// 保存数据库返回的用户信息

						if (type === 1) {
							// 返回无token, 另需获取手机号绑定对应的openid
							that.showPopup = true; // 显示获取手机号按钮
						} else {
							// 返回带token, 进入订单页
							let duration = 1500; // 延迟跳转页面
							uni.setStorageSync("token", res.data.accessToken)
							that.saveUserInfo(res.data); // 缓存用户基础数据
							that.sessionToken(res.data.accessToken); // 缓存token
							uni.showToast({
								title: '登录成功',
								duration
							})
							that.toTaskPage(duration);
						}
					} else {
						uni.showToast({
							title: res.msg
						})
					}
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.phonelogin {
		height: 49px;
		margin-top: 10 px;
		line-height: 49px;
		font-size: 16px;
		font-weight: 600;
		background: linear-gradient(to right, #04C15F, #1AC388);
		border-radius: 50rpx;
		color: #fff;
	}

	.login-box {
		position: relative;
		width: 100vw;
		height: 100vh;
		background: linear-gradient(180deg, rgba(26, 195, 136, 0.48) 0%, #FFFFFF 100%);
		border-radius: 0px 0px 0px 0px;
		opacity: 1;
	}

	.login-title {
		text-align: center;
		padding-top: 74rpx;
		font-size: 36rpx;
		color: #333333;
		font-weight: bold;
	}

	.logo {
		text-align: center;
		padding-top: 216rpx;

		image {
			width: 172rpx;
			height: 172rpx;
		}
	}

	.desc {
		text-align: center;
		padding-top: 48rpx;

		image {
			width: 284rpx;
			height: 46rpx;
		}
	}

	.form {
		width: 618rpx;
		margin: 0 auto;
		padding-top: 32rpx;

		.form_item {
			margin-top: 64rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100rpx;
			background: #FFFFFF;
			border-radius: 4px 4px 4px 4px;
			opacity: 1;
		}

		.label {
			width: 100rpx;
			margin-left: 15px;
			color: #666;
			font-size: 32rpx;
		}

		.inp1 {
			margin-left: 15px;
			margin-right: 15px;
			color: #666;
			flex: 1;
			font-size: 32rpx;
			line-height: 98rpx;
		}

		.pl {
			color: #999;
			font-size: 32rpx;
		}

	}

	.btn {
		width: 640rpx;
		height: 96rpx;
		line-height: 96rpx;
		color: #FFFFFF;
		background: linear-gradient(to right, #04C15F, #1AC388);
		font-size: 32rpx;
		border-radius: 8rpx;
		margin: 0 auto;
	}

	.other-login {
		position: relative;
		z-index: 5;
		width: 618rpx;
		margin: 80rpx auto 0;

		.ol-tilte {
			display: flex;

			align-items: center;
			justify-content: center;

			&:before,
			&:after {
				display: block;
				content: '';
				width: 30%;
				border-bottom: 2rpx solid #EFEFEF;
			}

			text {
				color: #666;
				font-size: 26rpx;
				padding: 0 20rpx;
			}
		}

		.wx-login {
			width: 88rpx;
			height: 88rpx;
			margin: 40rpx auto 0;

			image {
				display: block;
				width: 100%;
				height: 100%;
			}
		}
	}

	.bottom_img {
		position: absolute;
		left: 0;
		bottom: 0;
		display: block;
		width: 100%;
	}

	.popup-box {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 10;
		background-color: rgba(0, 0, 0, .5);
	}

	.login-popup {
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		z-index: 10;
		background-color: #fff;
		padding-bottom: 40rpx;

		.lp-top {
			display: flex;
			align-items: center;
			color: #000;
			line-height: 1.2;

			.lpt-left {
				flex: 1;
				padding: 30rpx;

				.title {
					font-size: 28rpx;
					font-weight: 500;
				}

				.tips {
					color: #9a9b9b;
					font-size: 18rpx;
					margin-top: 10rpx;
				}
			}

			.lpt-right {
				padding: 30rpx;

				image {
					display: block;
					width: 28rpx;
					height: 28rpx;
				}
			}
		}

		.lp-center {
			position: relative;
			padding: 10rpx 30rpx 40rpx;
			color: #000;

			&:after {
				position: absolute;
				bottom: 0;
				left: 30rpx;
				right: 30rpx;
				content: '';
				border-bottom: 1rpx solid #ededed;
			}

			.title {
				font-size: 28rpx;
				font-weight: 600;
			}

			.tips {
				font-size: 26rpx;
				margin-top: 10rpx;
			}
		}

		.lp-bottom {
			padding: 0 30rpx;
			margin-top: 40rpx;

			.option-btn {
				height: 86rpx;
				color: #fff;
				font-size: 22rpx;
				text-align: center;
				line-height: 86rpx;
				padding: 0 30rpx;
				background: linear-gradient(to right, #04C15F, #1AC388);
			}
		}
	}
</style>